using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlantNode : MonoBehaviour
{
    public float m_GrowSpeed_L = 0.05f; // length 
    public float m_GrowSpeed_W = 0.05f; // width
    public Transform m_NewBud_prefrab;

    private struct BudPosPair
    {
        public Vector3 localPos;
        public Transform bud;
    }
    private List<BudPosPair> m_ChildNodes = new List<BudPosPair>();

    // Use this for initialization
    void Awake()
    {

    }

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Grow();

        // carry buds together with growth
        foreach (BudPosPair pair in m_ChildNodes)
        {
            Vector3 worldPos = transform.TransformPoint(pair.localPos);
            pair.bud.transform.position = worldPos;
            //Debug.DrawRay(worldPos, Vector3.right);
        }
    }

    private float GetHeight()
    {
        // need to reinforce implementation properly
        return GetComponentInChildren<CapsuleCollider>().height;
    }

    private void Grow()
    {
        //transform the scale
        Vector3 newScale = transform.localScale;
        if (newScale.x < 3.0f)
            newScale.x = newScale.z = (newScale.x + m_GrowSpeed_W * Time.deltaTime);

        if (newScale.y < 10.0f)
            newScale.y = newScale.y + m_GrowSpeed_L * Time.deltaTime;

        // assign outpout
        transform.localScale = newScale;
    }

    // randomly spawn a bud onto this stem.
    public void Spawn()
    {
        if (m_NewBud_prefrab)
        {
            // spawn pos (local, then we have to carry this local list and calculate the world pos everyframe and attach the new buds onto it)
            BudPosPair pair = new BudPosPair();
            pair.localPos = transform.localPosition;
            // TODO: .. need a more realistic randomizing, preferrably higher density at top and lower at bottom
            pair.localPos.y = GetHeight() * Random.value;

            // spawn orientation
            // rotate xz to be +-80 degree, rotated locally.
            // rotate  y to be anything.. 360 degree.
            Vector3 euler_l = transform.localEulerAngles;
            euler_l.x += Random.Range(-80.0f, 80.0f);
            euler_l.z += Random.Range(-80.0f, 80.0f);
            euler_l.y += Random.Range(.0f, 360.0f);

            // spawn new tree node..
            pair.bud = Instantiate(m_NewBud_prefrab) as Transform;
            //print("spawngin..." + pair.bud);
            pair.bud.transform.localEulerAngles = euler_l;
            m_ChildNodes.Add(pair);
        }
    }
}

